package main.java.com.healthy.dao.impl;


import main.java.com.healthy.dao.FoodDAO;
import main.java.com.healthy.entity.Food;
import main.java.com.healthy.util.FileUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 食物数据访问实现类
 */
public class FoodDAOImpl implements FoodDAO {

    private static final String FOOD_FILE = "data/foods.dat";
    private List<Food> foods;

    public FoodDAOImpl() {
        loadFoods();
    }

    @Override
    public boolean addFood(Food food) {
        try {
            // 生成唯一食物ID
            if (food.getFoodId() == null || food.getFoodId().isEmpty()) {
                food.setFoodId(generateFoodId());
            }

            // 检查食物名称是否已存在（不区分大小写）
            if (getFoodByExactName(food.getFoodName()) != null) {
                System.out.println("食物名称已存在: " + food.getFoodName());
                return false;
            }

            foods.add(food);
            return saveFoods();
        } catch (Exception e) {
            System.err.println("添加食物失败: " + e.getMessage());
            return false;
        }
    }

    @Override
    public boolean updateFood(Food food) {
        try {
            for (int i = 0; i < foods.size(); i++) {
                if (foods.get(i).getFoodId().equals(food.getFoodId())) {
                    foods.set(i, food);
                    return saveFoods();
                }
            }
            return false;
        } catch (Exception e) {
            System.err.println("更新食物失败: " + e.getMessage());
            return false;
        }
    }

    @Override
    public boolean deleteFood(String foodId) {
        try {
            boolean removed = foods.removeIf(food -> food.getFoodId().equals(foodId));
            if (removed) {
                return saveFoods();
            }
            return false;
        } catch (Exception e) {
            System.err.println("删除食物失败: " + e.getMessage());
            return false;
        }
    }

    @Override
    public Food getFoodById(String foodId) {
        return foods.stream()
                .filter(food -> food.getFoodId().equals(foodId))
                .findFirst()
                .orElse(null);
    }

    @Override
    public List<Food> getAllFoods() {
        return new ArrayList<>(foods);
    }

    @Override
    public List<Food> getFoodsByCategory(String category) {
        return foods.stream()
                .filter(food -> food.getCategory().equals(category))
                .collect(Collectors.toList());
    }

    @Override
    public List<Food> searchFoodsByName(String keyword) {
        return foods.stream()
                .filter(food -> food.getFoodName().toLowerCase().contains(keyword.toLowerCase()))
                .collect(Collectors.toList());
    }

    @Override
    public List<String> getAllCategories() {
        return foods.stream()
                .map(Food::getCategory)
                .distinct()
                .collect(Collectors.toList());
    }

    @Override
    public List<Food> getCustomFoods(String userId) {
        return foods.stream()
                .filter(Food::isCustom)
                .filter(food -> food.getFoodId().startsWith("CUSTOM_" + userId + "_"))
                .collect(Collectors.toList());
    }

    @Override
    public Food getFoodByExactName(String foodName) {
        return foods.stream()
                .filter(food -> food.getFoodName().equalsIgnoreCase(foodName))
                .findFirst()
                .orElse(null);
    }

    /**
     * 生成唯一食物ID
     */
    private String generateFoodId() {
        return "FOOD_" + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
    }

    /**
     * 加载食物数据
     */
    @SuppressWarnings("unchecked")
    private void loadFoods() {
        try {
            Object data = FileUtil.readObject(FOOD_FILE);
            if (data instanceof List) {
                foods = (List<Food>) data;
            } else {
                foods = new ArrayList<>();
                // 初始化默认食物数据
                initializeDefaultFoods();
            }
        } catch (Exception e) {
            System.err.println("加载食物数据失败: " + e.getMessage());
            foods = new ArrayList<>();
            initializeDefaultFoods();
        }
    }

    /**
     * 保存食物数据
     */
    private boolean saveFoods() {
        try {
            return FileUtil.writeObject(FOOD_FILE, foods);
        } catch (Exception e) {
            System.err.println("保存食物数据失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 初始化默认食物数据
     */
    private void initializeDefaultFoods() {
        List<Food> defaultFoods = new ArrayList<>();

        // 主食类
        defaultFoods.add(new Food("F001", "米饭", "主食", 116, 25.6, 2.6, 0.3));
        defaultFoods.add(new Food("F002", "面条", "主食", 138, 28.0, 4.0, 0.8));
        defaultFoods.add(new Food("F003", "馒头", "主食", 223, 47.0, 7.0, 1.0));
        defaultFoods.add(new Food("F004", "面包", "主食", 265, 50.6, 8.3, 3.1));
        defaultFoods.add(new Food("F005", "燕麦", "主食", 367, 66.2, 12.5, 7.0));

        // 肉类
        defaultFoods.add(new Food("F006", "鸡胸肉", "肉类", 165, 0, 31.0, 3.6));
        defaultFoods.add(new Food("F007", "牛肉", "肉类", 250, 0, 26.0, 15.0));
        defaultFoods.add(new Food("F008", "猪肉", "肉类", 242, 0, 18.0, 18.0));
        defaultFoods.add(new Food("F009", "鱼肉", "肉类", 127, 0, 22.0, 4.0));
        defaultFoods.add(new Food("F010", "虾", "肉类", 85, 0, 18.0, 1.0));

        // 蛋类
        defaultFoods.add(new Food("F011", "鸡蛋", "蛋类", 155, 1.1, 13.0, 11.0));
        defaultFoods.add(new Food("F012", "鸭蛋", "蛋类", 180, 2.0, 13.0, 14.0));

        // 乳制品
        defaultFoods.add(new Food("F013", "牛奶", "乳制品", 54, 5.0, 3.0, 3.2));
        defaultFoods.add(new Food("F014", "酸奶", "乳制品", 72, 9.3, 2.5, 2.7));
        defaultFoods.add(new Food("F015", "奶酪", "乳制品", 328, 1.5, 25.0, 27.0));

        // 蔬菜类
        defaultFoods.add(new Food("F016", "西兰花", "蔬菜", 34, 6.6, 2.8, 0.4));
        defaultFoods.add(new Food("F017", "胡萝卜", "蔬菜", 41, 9.6, 1.0, 0.2));
        defaultFoods.add(new Food("F018", "西红柿", "蔬菜", 18, 3.9, 0.9, 0.2));
        defaultFoods.add(new Food("F019", "黄瓜", "蔬菜", 15, 3.6, 0.7, 0.1));
        defaultFoods.add(new Food("F020", "菠菜", "蔬菜", 23, 3.6, 2.9, 0.4));

        // 水果类
        defaultFoods.add(new Food("F021", "苹果", "水果", 52, 13.8, 0.3, 0.2));
        defaultFoods.add(new Food("F022", "香蕉", "水果", 89, 22.8, 1.1, 0.3));
        defaultFoods.add(new Food("F023", "橙子", "水果", 47, 11.8, 0.9, 0.1));
        defaultFoods.add(new Food("F024", "葡萄", "水果", 69, 18.1, 0.7, 0.2));
        defaultFoods.add(new Food("F025", "西瓜", "水果", 30, 7.6, 0.6, 0.2));

        // 豆制品
        defaultFoods.add(new Food("F026", "豆腐", "豆制品", 76, 1.9, 8.1, 4.2));
        defaultFoods.add(new Food("F027", "豆浆", "豆制品", 33, 1.8, 3.3, 1.6));
        defaultFoods.add(new Food("F028", "黄豆", "豆制品", 390, 34.2, 35.0, 16.0));

        foods.addAll(defaultFoods);
        saveFoods();
    }
}